<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" :rules="rules" ref="loginForms">
          <h1>Hello</h1>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" :prefix-icon="User"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="loginForm.password" :prefix-icon="Lock" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="login_btn" type="primary" @click="login" :loading="isLoading">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
import {User,Lock} from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user.ts'
import { useRouter} from 'vue-router'
import {ElNotification} from "element-plus";
import {getTime} from '@/utils/time.ts'

const isLoading = ref(false);

const $router = useRouter();
const loginForm = ref({
  username:'admin',
  password:'ABCabc123'
})
const loginForms = ref()
const userStore = useUserStore()
const login = async () => {
  await loginForms.value.validate()

  isLoading.value = true;
  try {
    await userStore.userLogin(loginForm.value);
    $router.push('/home')
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: `Hi,${loginForm.value.username}${getTime()}`
    })
    isLoading.value = false;
  } catch (e) {
    isLoading.value = false;
    ElNotification({
      type: 'error',
      message: e.message
    })
  }
}
const checkPassword1 = (rule:any,value:string,callback:any) =>{
  //rule 数组校验对象
  //value 文本内容
  //callback 回调函数
  if(value.length<6){
    callback(new Error('密码长度不能小于6位'))
  }else if(!value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/)){
    callback(new Error('密码必须包含字母和数字'))
  }else{
    callback()
  }

}
//表单校验
const rules = {
  username:[
      {required:true,message:'请输入用户名',trigger:'blur'},
      {min:2,max:10,message:'长度在2-10个字符',trigger:'change'}
  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {trigger: 'change',validator: checkPassword1}
  ]
}

</script>

<style scoped lang="scss">
.login_container{
  width: 100%;
  height: 100vh;
  background: url("@/assets/images/background.jpg") no-repeat;
  background-size: cover;
  overflow-y: hidden;
  .login_form{
    position: relative;
    width: 60%;
    top: 30vh;
    background: url("@/assets/images/login_form.png") no-repeat;
    background-size: cover;
    padding: 40px;
    h1{
      color: white;
      font-size: 40px;
    }
    .login_btn{
      width: 100%;
    }
  }
}
</style>
